namespace Brjnk.GpxExplorer.Localization
{
    using System;
    using System.Linq;
    using System.Xml.Serialization;

    /// <summary>
    /// </summary>
    public struct IsoLanguageName : IXmlSerializable
    {
        private string name;

        public string Name { get { return name; } }

        public string FullName { get; private set; }

        public string NativeName { get; private set; }

        public bool IsValid { get; private set; }

        public IsoLanguageName(string name)
            : this()
        {
            Initialize(name);
        }

        private void Initialize(string name)
        {
            this.name = name;
            var culture = System.Globalization.CultureInfo.GetCultures(System.Globalization.CultureTypes.AllCultures).Where(c => string.Equals(name, c.ThreeLetterISOLanguageName, StringComparison.InvariantCultureIgnoreCase)).FirstOrDefault();
            if (culture != null)
            {
                FullName = culture.EnglishName;
                NativeName = culture.NativeName;
                IsValid = true;
            }
        }

        public override bool Equals(object obj)
        {
            if (obj == null) return false;
            if (obj.GetType() != typeof(IsoLanguageName)) return false;
            var second = (IsoLanguageName)obj;
            return string.Equals(second.name, this.name, StringComparison.InvariantCultureIgnoreCase);
        }

        public override int GetHashCode()
        {
            return this.name.ToUpper().GetHashCode();
        }

        public static implicit operator string(IsoLanguageName lang)
        {
            return lang.name;
        }

        public System.Xml.Schema.XmlSchema GetSchema()
        {
            throw new NotImplementedException();
        }

        public void ReadXml(System.Xml.XmlReader reader)
        {
            name = reader.ReadElementContentAsString();
            Initialize(name);
        }

        public void WriteXml(System.Xml.XmlWriter writer)
        {
            writer.WriteString(name);
        }
    }
}